/*
 * @Description: 导出
 * @Author: chenju
 * @Date: 2022-01-25 15:00:41
 * @LastEditors: qingyang
 * @LastEditTime: 2023-07-03 17:07:27
 */
import { ElLoading } from 'element-plus/lib/components';
import { useMessage } from './useMessage';
import { downloadFile } from '@/utils/file';
import { ref } from 'vue';
import domtoimage from 'dom-to-image';
import { uploadImg } from '@/apis/common/common';
import type { AxiosResponse } from 'axios';
import { AllBizScopeEnum } from '@/commonModule/constants';

type IType = 'FILE' | 'DataURL' | 'IMAGE' | 'URL' | 'OTHER';
export const useExport = () => {
  const { createMessage } = useMessage();
  const imgLoading = ref(false);
  const imgsLoading = ref(false);
  async function handleExportFile<T = any>(
    loadData: (params: T) => Promise<AxiosResponse<Blob>>,
    params: T,
    successText = '操作成功！'
  ) {
    const result = loadData(params);
    if (
      (typeof result === 'object' || typeof result === 'function') &&
      typeof result.then === 'function'
    ) {
      let imgLoadingInstance: any = ElLoading.service({
        fullscreen: true,
        lock: true,
        text: '文件导出中...',
        background: 'rgba(0, 0, 0, 0.7)',
        customClass: 'g-export-file-loading'
      });

      const timer = setTimeout(() => {
        if (imgLoadingInstance) {
          imgLoadingInstance.close();
          createMessage.error('导出超时！');
          return Promise.reject('导出超时！');
        }
      }, 60000);

      try {
        const res = await result;
        const headerFileName = res.headers['content-disposition'];
        const { fileName, suffix } = getFileName(headerFileName);
        // 下载二进制流
        await downloadFile(res.data, fileName, suffix, false);
        createMessage.success(successText);
        return Promise.resolve(true);
      } catch (error: any) {
        console.log('导出error', error);
        createMessage.error(error.message || error);
        return Promise.reject(error);
      } finally {
        imgLoadingInstance && imgLoadingInstance.close();
        imgLoadingInstance = null;
        clearTimeout(timer);
        console.log('finally imgLoadingInstance', imgLoadingInstance);
      }
    } else {
      console.error('输入方法异常');
      return Promise.reject('输入方法异常');
    }
  }

  /**
   * 获取文件名称及后缀
   * @param headerFileName 接口返回的 content-disposition
   * @param defaultFileName 默认文件名
   * @param defaultSuffix 默认后缀名
   * @returns
   */
  function getFileName(
    headerFileName: string,
    defaultFileName = '导出文件',
    defaultSuffix = 'xlsx'
  ) {
    let fileName = defaultFileName;
    let suffix = defaultSuffix;
    if (headerFileName && headerFileName.includes('filename')) {
      const fileArr = headerFileName && headerFileName.split("filename*=utf-8''");
      const fileNameAll = decodeURIComponent(fileArr[1]);
      const suffixArr = fileNameAll.split('.');
      if (suffixArr && suffixArr.length == 2) {
        suffix = suffixArr[1];
        fileName = suffixArr[0];
      } else if (suffixArr.length > 2) {
        suffix = suffixArr[-1];
        fileName = suffixArr.slice(0, -1).join('.');
      }
    }
    return {
      suffix,
      fileName
    };
  }

  /**
   * dom转图片
   * @param id  dom的id带#
   * @param type
   * @returns
   */
  const handleDomToImg = (id: string, type: IType = 'URL', name = 'test'): Promise<any> => {
    const pic: HTMLElement | null = document.querySelector(id);
    return new Promise((resolve, reject) => {
      if (pic) {
        imgLoading.value = true;
        if (type === 'IMAGE' || type === 'DataURL') {
          domtoimage.toPng(pic, { quality: 1 }).then((dataUrl: string) => {
            const img = new Image();
            img.src = dataUrl;
            return resolve(type == 'IMAGE' ? img : dataUrl);
          });
        } else {
          domtoimage.toBlob(pic, { quality: 1, bgcolor: '#FFF' }).then((blob: Blob) => {
            if (type === 'FILE') {
              const file: any = new File([blob], `${name}`, { type: blob.type });
              file.uid = Date.now();
              downloadFile(blob, file.name, 'jpeg');
              // downloadFile(blob, 'test', 'png');
              return resolve(file);
            }
            if (type === 'OTHER') {
              const file: any = new File([blob], `${id.substring(1)}.png`, { type: blob.type });
              file.uid = Date.now();
              // downloadFile(blob, file.name, 'png');
              return resolve(file);
            }
            if (type === 'URL') {
              const file: any = new File([blob], `${id.substring(1)}.png`, { type: blob.type });
              file.uid = Date.now();
              const formData = new FormData();
              formData.append('file', file);
              formData.append('groupType', 'PCF_MODEL_INFO');
              formData.append('scope', AllBizScopeEnum.PCF);
              formData.append('needRename', 'false');
              uploadImg(formData)
                .then((res: any) => {
                  imgLoading.value = false;
                  resolve(res.fileUrl);
                })
                .catch(() => {
                  imgLoading.value = false;
                  reject();
                });
            }
          });
        }
      } else {
        createMessage.error('dom对象不存在');
        reject();
      }
    });
  };

  /**
   * 多个dom转图片
   * @param ids  dom的id带#
   * @param type
   * @returns
   */
  const handleDomsToImgs = (ids: string[], type: IType = 'URL'): Promise<any> => {
    return new Promise((resolve, reject) => {
      imgsLoading.value = true;
      const promiseArr = ids.map((item: string) => {
        return handleDomToImg(item, type);
      });
      Promise.all(promiseArr)
        .then(res => {
          imgsLoading.value = false;
          resolve(res);
        })
        .catch(() => {
          imgsLoading.value = false;
          reject();
        });
    });
  };
  return {
    imgLoading,
    imgsLoading,
    handleExportFile,
    handleDomToImg,
    handleDomsToImgs
  };
};
